﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LastStoneWeight
{
    public class Solution
    {
        public int LastStoneWeight(int[] stones)
        {
            var list = stones.ToList();

            while (list.Count > 1)
            {
                int first = FindMax(list);
                int second = FindMax(list);

                if (first != second)
                {
                    list.Add(first > second ? first - second : second - first);
                }

            }

            return list.Count > 0 ? list[0] : 0;
        }

        private int FindMax(List<int> list)
        {
            //int maxIndex = 0;
            //for (int i = 1; i < list.Count; i++)
            //{
            //    if (list[i] > list[maxIndex])
            //    {
            //        maxIndex = i;
            //    }
            //}

            //int max = list[maxIndex];
            //list.RemoveAt(maxIndex);

            var max = list.Max();
            var index = list.IndexOf(max);
            list.RemoveAt(index);

            return max;
        }
    }
}
